#!/usr/bin/python3
# coding=utf-8
#
# Copyright (C) 2023-2024. Huawei Technologies Co., Ltd. All rights reserved.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# ===============================================================================

import sys
import numpy as np

# for float32
relative_tol = 1e-5
absolute_tol = 1e-8
error_tol = 1e-3

def verify_result(output, golden):
    output = np.fromfile(output, dtype=np.float32).reshape(-1)
    golden = np.fromfile(golden, dtype=np.float32).reshape(-1)
    different_element_results = np.isclose(output,
                                           golden,
                                           rtol=relative_tol,
                                           atol=absolute_tol,
                                           equal_nan=True)
    different_element_indexes = np.where(different_element_results == False)[0]
    
    # 打印所有结果的详细信息
    print("=== Verification Results ===")
    max_show = 50  # 只打印前 50 行
    for index in range(min(len(output), max_show)):
        golden_data = golden[index]
        output_data = output[index]
        is_close = different_element_results[index]
        status = "PASS" if is_close else "FAIL"
        rdiff = abs(output_data - golden_data) / golden_data if golden_data != 0 else (0.0 if output_data == 0 else float('inf'))
        print(f"data index: {index:06d}, expected: {golden_data:.9f}, actual: {output_data:.9f}, rdiff: {rdiff:.6f} , status: {status}")
    if len(output) > max_show:
        print(f"... (omit {len(output)-max_show} lines)")
        
    # 如果有错误，额外打印错误详情
    if len(different_element_indexes) > 0:
        print("\n=== Error Details ===")
        for index in range(min(len(different_element_indexes), 10)):  # 限制打印前10个错误
            real_index = different_element_indexes[index]
            golden_data = golden[real_index]
            output_data = output[real_index]
            print(
                "data index: %06d, expected: %-.9f, actual: %-.9f, rdiff: %-.6f" %
                (real_index, golden_data, output_data,
                 abs(output_data - golden_data) / golden_data if golden_data != 0 else float('inf')))
    
    error_ratio = float(different_element_indexes.size) / golden.size
    print("\nerror ratio: %.4f, tolerance: %.4f" % (error_ratio, error_tol))
    return error_ratio <= error_tol


if __name__ == '__main__':
    try:
        res = verify_result(sys.argv[1], sys.argv[2])
        if not res:
            print("[ERROR] result error")
            sys.exit(1)
        else:
            print("test pass")
    except Exception as e:
        print(e)
        sys.exit(1)